<template>
    <div>
        <!-- <div>
            <el-button @click="this.$router.push({name: 'myTickets'})" type="text" icon="el-icon-back">返回</el-button>
        </div> -->
        <h1>活动信息</h1>
        <el-link type="primary" @click="goToEvent()" style="font-size: 25px;">{{eventInfo.title}}</el-link><br>
        主办方：{{eventInfo.organizer_name}}<br>
        时间：{{eventInfo.start_time}} 至 {{eventInfo.end_time}}<br>
        地点：{{eventInfo.location}}
        <el-divider></el-divider>

        <h1>票据信息</h1>
        <h3>NFT编号：{{LIFEId}}</h3>
        <h3 class="event-status">{{status}}</h3>
        票种名称：{{ticketInfo.name}}<br>
        价格：¥ {{ticketInfo.price}}<br>
        售票截止时间：{{ticketInfo.saleEndTime}}<br>
        <div v-if="ticketInfo.returnable">
            可退票，截止时间：{{ticketInfo.returnEndTime}}<br>
        </div>
        <div v-if="ticketInfo.transferable">
            可转售，截止时间：{{ticketInfo.transferEndTime}}<br>
            可赠予，截止时间：{{ticketInfo.transferEndTime}}<br>
        </div>
        有效期截止时间：{{ticketInfo.validBefore}}<br>
        单人最多购买{{ticketInfo.maxNum}}张票<br>
        说明：{{ticketInfo.description}}<br>
        <el-divider></el-divider>

        <el-button :disabled="LIFEInfo.used" type="success" @click="checkIn()">验票</el-button>
        <el-button v-if="LIFEInfo.used" type="primary" @click="openReviewDialog()">评价</el-button>
        <el-button v-if="ticketInfo.returnable" :disabled="!returnable" type="primary" @click="returnTicket()">退票</el-button>
        <el-button v-if="!LIFEInfo.toBeResold && ticketInfo.transferable" :disabled="!resellable" type="primary" @click="resellTicket()">转售</el-button>               
        <el-button v-if="LIFEInfo.toBeResold && ticketInfo.transferable" type="primary" @click="cancelReselling()">取消转售</el-button>               
        <el-button v-if="!LIFEInfo.toBeAccepted && ticketInfo.transferable" :disabled="!grantable" type="primary" @click="openGrantDialog()">赠予</el-button>               
        <el-button v-if="LIFEInfo.toBeAccepted && ticketInfo.transferable" type="primary" @click="cancelGranting()">取消赠予</el-button>               

        <el-dialog :visible.sync="dialogVisible_grant" width="500px" center>
            <h3 v-if="granteeList.length == 0">未设置可赠予人名单，不可赠予</h3>
            <div style="height: 50px;" v-if="granteeList.length > 0">
                <el-select v-model="granteeIndex">
                    <el-option
                        v-for="(g, gIndex) in granteeList"
                        :key="gIndex"
                        :label="g.username"
                        :value="gIndex">
                    </el-option>
                </el-select>
            </div>
            <span slot="footer" v-if="granteeList.length > 0">
                <el-button type="primary" @click="grantTicket()">提交</el-button>
            </span>
        </el-dialog>

        <el-dialog title="评价" :visible.sync="dialogVisible_review" width="500px" center>
            <div>
                评分：<br><br>
                <el-rate v-model="review.score"></el-rate><br>
                评论：<br><br>
                <el-input v-model="review.comment" placeholder="" type="textarea"></el-input>
            </div>
            <span slot="footer">
                <el-button type="primary" @click="submitReview()">提交</el-button>
            </span>
        </el-dialog>
    </div>

    
</template>

<script>
import common from "../../utils/common.vue";
import {mapGetters} from 'vuex';

export default {
    data() {
        return {
            dialogVisible_grant: false,
            dialogVisible_review: false,
            eventInfo: {
                id: '',
                title: '',
                location: '',
                start_time: '',
                end_time: '',
                organizer_name: '',
                organizer_id: '',
            },
            ticketInfo: {
                id: '',
                name: '',
                price: '',
                sum: '',
                maxNum: '',
                returnable: false,
                transferable: false,
                validBefore: '',
                saleEndTime: '',
                returnEndTime: '',
                transferEndTime: '',
                description: '',
            },
            LIFEId: '',
            LIFEInfo: {
                ticketId: '',
                used: false,
                toBeResold: false,
                toBeAccepted: false,
            },
            status: '',
            returnable: false,
            resellable: false,
            grantable: false,
            granteeList: [],
            granteeIndex: '',
            review: {
                comment: '',
                score: 0,
            },
        }
    },
    created() {
        this.eventInfo.id = this.$route.params.event_id;
        this.ticketInfo.id = this.$route.params.id;
        this.LIFEId = this.$route.params.LIFEId;
        this.getEventBasicInfo();
        this.getTicketInfo();
        this.getGranteeList();
    },
    computed: {
        ...mapGetters([
            'userId',
            'username',
            'address',
        ]),
    },
    methods: {
        getEventBasicInfo() {
            this.api({
                url: "/event/getEventBasicInfo",
                method: "post",
                data: {id: this.eventInfo.id}
            }).then(data => {
                this.eventInfo.title = data.info.title;
                this.eventInfo.location = data.info.location;
                this.eventInfo.start_time = data.info.start_time;
                this.eventInfo.end_time = data.info.end_time;
                this.eventInfo.organizer_name = data.info.organizer_name;
                this.eventInfo.organizer_id = data.info.organizer_id;  
            })
        },
        getTicketInfo() {
            this.api({
                url: "/event/getTicketById",
                method: "post",
                data: {id: this.ticketInfo.id}
            }).then(data => {
                this.ticketInfo.name = data.info.name;
                this.ticketInfo.price = data.info.price;
                this.ticketInfo.sum = data.info.sum;
                this.ticketInfo.maxNum = data.info.maxNum;
                this.ticketInfo.returnable = data.info.returnable;
                this.ticketInfo.transferable = data.info.transferable;
                this.ticketInfo.validBefore = data.info.validBefore;
                this.ticketInfo.saleEndTime = data.info.saleEndTime;
                this.ticketInfo.returnEndTime = data.info.returnEndTime;
                this.ticketInfo.transferEndTime = data.info.transferEndTime;
                this.ticketInfo.description = data.info.description;
                this.getLIFEInfo();
            })
        },
        getLIFEInfo() {
            this.api({
                url:"/ticketing/getLIFEInfo",
                method: "post",
                data: {LIFEId: this.LIFEId, userId: this.userId}
            }).then(data => {    
                if (data.code == common.codeFromBackEnd.SUCCESS_CODE) {
                    this.LIFEInfo.ticketId = data.info.ticketId;
                    this.LIFEInfo.used = data.info.used;
                    this.LIFEInfo.toBeResold = data.info.toBeResold;
                    this.LIFEInfo.toBeAccepted = data.info.toBeAccepted;
                    this.getStatus();
                    this.getAbility();
                } else {
                    this.$message.error(data.msg);
                } 
            }).catch((err) => {
                console.log('err:',err)
                this.$message.error("获取票据信息失败")
            })
        },
        getGranteeList() {
            this.api({
                url:"/ticketing/getGranteeList",
                method: "post",
                data: {LIFEId: this.LIFEId, userId: this.userId}
            }).then(data => {    
                this.granteeList = data.info;
            }).catch((err) => {
                console.log('err:',err)
                this.$message.error("失败")
            })
        },
        getStatus() {
            let now = Date.now();
            let validBefore = new Date(this.ticketInfo.validBefore).getTime();
            let saleEndTime = new Date(this.ticketInfo.saleEndTime).getTime();
            let transferEndTime = new Date(this.ticketInfo.transferEndTime).getTime();
            if (this.LIFEInfo.used) {
                this.status = '已使用';
            } else if (now >= validBefore) { // && not used 
                this.status = '未使用';
            } else if (this.LIFEInfo.toBeAccepted && now < transferEndTime) { // && not used && before validBefore
                this.status = '待被赠予人接收';
            } else if (this.LIFEInfo.toBeResold && now < saleEndTime && now < transferEndTime) {
                this.status = '待转售';
            } else {
                this.status = '待使用';
            }
        },
        getAbility() {
            console.log("lifeinfo.toberesold", this.LIFEInfo.toBeResold == true)
            if (this.LIFEInfo.used || this.LIFEInfo.toBeResold || this.LIFEInfo.toBeAccepted) {
                this.returnable = false;
                this.resellable = false;
                this.grantable = false;
                return;
            }
            let now = Date.now();
            let saleEndTime = new Date(this.ticketInfo.saleEndTime).getTime();
            let returnEndTime = new Date(this.ticketInfo.returnEndTime).getTime();
            let transferEndTime = new Date(this.ticketInfo.transferEndTime).getTime();
            if (this.ticketInfo.returnable) {
                this.returnable = (now < returnEndTime) ? true : false;
            } else {
                this.returnable = false;
            }
            if (this.ticketInfo.transferable) {
                this.resellable = (now < transferEndTime && now < saleEndTime) ? true : false;
                this.grantable = (now < transferEndTime) ? true : false;
            } else {
                this.resellable = false;
                this.grantable = false;
            }
        },
        returnTicket() {
            this.api({
                url:"/ticketing/returnTicket",
                method: "post",
                data: {LIFEId: this.LIFEId, userId: this.userId}
            }).then(data => {    
                if (data.code == common.codeFromBackEnd.SUCCESS_CODE) {
                    this.$message({
                        message: "成功退票",
                        type: 'success'
                    }) 
                    this.$router.push({name: 'myTickets'});
                } else {
                    this.$message.error(data.msg);
                } 
            }).catch((err) => {
                console.log('err:',err)
                this.$message.error("退票失败")
            })
        },
        resellTicket() {
            this.api({
                url:"/ticketing/resellTicket",
                method: "post",
                data: {                   
                    LIFEId: this.LIFEId, 
                    ticketId: this.LIFEInfo.ticketId, 
                    deletableAfter: (this.ticketInfo.saleEndTime < this.ticketInfo.transferEndTime) ? this.ticketInfo.saleEndTime : this.ticketInfo.transferEndTime,
                    userId: this.userId
                }
            }).then(data => {    
                if (data.code == common.codeFromBackEnd.SUCCESS_CODE) {
                    this.$message({
                        message: "成功提交转售申请",
                        type: 'success'
                    }) 
                } else {
                    this.$message.error(data.msg);
                } 
                this.getLIFEInfo();
            }).catch((err) => {
                console.log('err:',err)
                this.$message.error("操作失败")
            })
        },
        cancelReselling() {
            this.api({
                url:"/ticketing/cancelReselling",
                method: "post",
                data: {
                    LIFEId: this.LIFEId, 
                    ticketId: this.LIFEInfo.ticketId, 
                    userId: this.userId
                }
            }).then(data => {    
                if (data.code == common.codeFromBackEnd.SUCCESS_CODE) {
                    this.$message({
                        message: "成功取消转售",
                        type: 'success'
                    }) 
                } else {
                    this.$message.error(data.msg);
                } 
                this.getLIFEInfo();
            }).catch((err) => {
                console.log('err:',err)
                this.$message.error("操作失败")
            })
        },
        grantTicket() {
            this.api({
                url:"/ticketing/grantTicket",
                method: "post",
                data: {
                    LIFEId: this.LIFEId, 
                    userId: this.userId,
                    username: this.username,
                    ticketId: this.ticketInfo.id,
                    toAddress: this.granteeList[this.granteeIndex].address,
                    toId: this.granteeList[this.granteeIndex].userId,
                    ticketName: this.ticketInfo.name,
                    eventTitle: this.eventInfo.title,
                    eventId: this.eventInfo.id
                }
            }).then(data => {    
                if (data.code == common.codeFromBackEnd.SUCCESS_CODE) {
                    this.$message({
                        message: "请等待被赠予人接收",
                        type: 'success'
                    }) 
                } else {
                    this.$message.error(data.msg);
                } 
                this.getLIFEInfo();
            }).catch((err) => {
                console.log('err:',err)
                this.$message.error("赠予失败")
            })
            this.dialogVisible_grant = false;
        },
        cancelGranting() {
            this.api({
                url:"/ticketing/cancelGranting",
                method: "post",
                data: {
                    LIFEId: this.LIFEId, 
                    userId: this.userId
                }
            }).then(data => {    
                if (data.code == common.codeFromBackEnd.SUCCESS_CODE) {
                    this.$message({
                        message: "成功取消赠予",
                        type: 'success'
                    }) 
                } else {
                    this.$message.error(data.msg);
                } 
                this.getLIFEInfo();
            }).catch((err) => {
                console.log('err:',err)
                this.$message.error("操作失败")
            })
        },
        openGrantDialog() {
            this.grantee = '',
            this.dialogVisible_grant = true;
        },
        openReviewDialog() {
            this.review.comment = '',
            this.review.score = 0,
            this.dialogVisible_review = true;
        },
        submitReview() {
            this.api({
                url:"/review/addReview",
                method: "post",
                data: {
                    LIFEId: this.LIFEId,
                    userId: this.userId,
                    score: this.review.score,
                    comment: this.review.comment
                }
            }).then(data => {    
                if (data.code == common.codeFromBackEnd.SUCCESS_CODE) {
                    this.$message({
                        message: "评论成功",
                        type: 'success'
                    }) 
                } else {
                    this.$message.error(data.msg);
                } 
                this.getLIFEInfo();
            }).catch((err) => {
                console.log('err:',err)
                this.$message.error("操作失败")
            })
            this.dialogVisible_review = false;
        },
        goToEvent() {
            this.$router.push({
                name: 'event',
                params: {id: this.eventInfo.id}
            })
        },
        checkIn() {
            // temporary
            this.api({
                url:"/ticketing/checkIn",
                method: "post",
                data: {
                    LIFEId: this.LIFEId, 
                    userId: this.eventInfo.organizer_id
                }
            }).then(data => {    
                if (data.code == common.codeFromBackEnd.SUCCESS_CODE) {
                    this.$message({
                        message: "验票成功",
                        type: 'success'
                    }) 
                } else {
                    this.$message.error(data.msg);
                } 
                this.getLIFEInfo();
            }).catch((err) => {
                console.log('err:',err)
                this.$message.error("操作失败")
            })
        }
    },
}
</script>

<style scoped>
.event-status {
    font-size: 18px;
    color: #E6A23C;
}


</style>